package com.code.commons.util;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: whitecoin-dapp-parent
 * @description: Excel文件生成类
 * @author: hongchun
 * @date: 2020-02-15 18:15
 **/
public class ExcelUtil {

    /**
     * 导出Excel文件
     *
     * @param excelName
     * @param headList
     * @param dataList
     * @param response
     * @throws Exception
     */
    public static void export(String excelName, List<String> headList, List<List<String>> dataList, HttpServletResponse response) throws Exception {

        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);

            // 设置SHEET名称
            Sheet sheet = new Sheet(1, 0);
            sheet.setSheetName(excelName);
            // 设置标题
            Table table = new Table(1);
            table.setHead(buildExcelTitles(headList));

            writer.write0(dataList, sheet, table);

            // 下载EXCEL
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("utf-8"), "ISO8859-1") + ".xls");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            writer.finish();
            out.flush();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @description: 设置标题
     */
    private static List<List<String>> buildExcelTitles(List<String> titles) {
        return titles.stream().map(title -> Arrays.asList(title)).collect(Collectors.toList());
    }


}
